#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "socket.h"
#include "clientList.h"

pthread_mutex_t mutex;

void* parseRecvMessage(void* arg)
{
    struct clientInfo *info = (struct clientInfo*)arg;
    while(1)
    {
        char* buffer;
        enum Type t;
        int len = recvMessage(info->fd,&buffer,&t);
        if(buffer == NULL)
        {
            printf("fd = %d ,通信的子线程推出了\n",info->fd);
            pthread_exit(NULL);
        }
        else
        {
            if(t == Heart)
            {
                printf("心跳包，%s\n",buffer);
                pthread_mutex_lock(&mutex);
                info->count = 0;//接受到服务器发送过来的心跳包，count重置为0
                pthread_mutex_unlock(&mutex);
                sendMessage(info->fd,buffer,len,Heart);
            }
            else
            {
                const char* msg = "yidai";
                printf("数据包，%s\n",buffer);
                sendMessage(info->fd,msg,strlen(msg),Message);
            }
            free(buffer);
        }
    }
    return NULL;
}


void* heartBeat(void* arg)
{
    struct clientInfo *head = (struct clientInfo*)arg;
    struct clientInfo *p = NULL;
    while(1)   
    {
        p = head->next;
        while(p)
        {
            pthread_mutex_lock(&mutex);
            p->count++;
            printf("fd = %d,count = %d\n",p->fd,p->count);
            if(p->count > 5)
            {
                printf("客户端 fd = %d 与服务器断开连接\n",p->fd);
                //释放套接字资源
                close(p->fd);
                pthread_cancel(p->pid);
                eraseNode(head,p->fd);
            }
            pthread_mutex_unlock(&mutex);   
            p = p->next; 
        }
        sleep(3);
    }
    return NULL;
}
int main()
{
    unsigned short port = 8888;

    int fd = initSocket();
    setListen(fd,port);
    //创建存储客户端连接的链表
    struct clientInfo* head = createList();
    pthread_mutex_init(&mutex,NULL);

    //添加心跳包子线程
    pthread_t pid1;
    pthread_create(&pid1,NULL,heartBeat,head);
    while(1)
    {
        int sockfd = acceptConnect(fd,NULL);
        if(sockfd == -1)
        {
            continue;
        }
        printf("接受来自客户端的连接：%d\n",sockfd);
        struct clientInfo* node = pushFront(head,sockfd);
         //创建用于接受数据的子线程
        pthread_create(&node->pid,NULL,parseRecvMessage,node); 
        pthread_detach(node->pid);
        sleep(2);
    }
    
    pthread_join(pid1,NULL);
    pthread_mutex_destroy(&mutex);
    close(fd);
    return 0;
}